package cn.edu.jnu.basicms.controller;

import cn.edu.jnu.basicms.common.Page;
import cn.edu.jnu.basicms.common.Result;
import cn.edu.jnu.basicms.entity.User;
import cn.edu.jnu.basicms.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    // 新增用户
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            userService.insert(user);
            return Result.success("新增成功");
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry")) {
                return Result.error("用户名已存在");
            }
            return Result.error("新增失败");
        }
    }

    // 修改用户
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success("修改成功");
    }

    // 删除单个用户
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.deleteUser(id);
        return Result.success("删除成功");
    }

    // 批量删除用户
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        userService.deleteBatchUser(ids);
        return Result.success("批量删除成功");
    }

    // 查询所有用户
    @GetMapping("/list")
    public Result list() {
        List<User> userList = userService.selectAll();
        return Result.success(userList);
    }

    // 根据ID查询用户
    @GetMapping("/get/{id}")
    public Result get(@PathVariable Integer id) {
        User user = userService.selectById(id);
        return Result.success(user);
    }

    // 根据姓名模糊查询
    @GetMapping("/search")
    public Result search(@RequestParam String name) {
        List<User> userList = userService.selectByName(name);
        return Result.success(userList);
    }

    // 多条件查询
    @GetMapping("/searchByMultipleConditions")
    public Result searchByMultipleConditions(@RequestParam Map<String, Object> conditions) {
        List<User> users = userService.selectByMultipleConditions(conditions);
        return Result.success(users);
    }

    // 分页模糊查询
    @GetMapping("/searchByPage")
    public Result searchByPage(@RequestParam String name, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        Page<User> pageResult = userService.selectByPageAndName(name, pageNum, pageSize);
        return Result.success(pageResult);
    }
}